//Fetch.scala
package mycore

import chisel3._
import chisel3.util._

class Fetch extends Module{
  val io = IO(new Bundle{

    val ENABLE = Input(Bool())
    val ifid = new IFID
    val InstFetch = new InstFetch
    val cancel = Input(Bool())
    val nextPC = Flipped(new NEXTPC)

    val isSoC = Input(Bool())
    
  })

  //本流水级需要使用的信号
  val initPC = Mux(io.isSoC, "h0000000030000000".U(64.W), "h0000000080000000".U(64.W))

  val Valid = Mux(reset.asBool(), false.B, true.B)
  val Inst = io.InstFetch.data
  val PC = RegInit(initPC)

  /*------------------------------*/
  /*             本体             */
  /*------------------------------*/

  when(io.ENABLE) {
    when(io.nextPC.trap){
      PC := io.nextPC.mtvec
    }.elsewhen(io.nextPC.mret){
      PC := io.nextPC.mepc
    }.elsewhen(io.nextPC.branch){
      PC := io.nextPC.target
    }.otherwise{
      PC := PC + 4.U
    }
  }
  /*------------------------------*/

  //传递给下一个流水级的信号
  io.ifid.Valid := Mux(io.cancel, false.B, Valid)
  io.ifid.Inst := Inst
  io.ifid.PC := PC


  //IO
  io.InstFetch.en := Valid
  io.InstFetch.addr := PC
}